Page({
  data: {
    token: {},
    name: '加载中...',
    number: '',
    status: '',
    officerInfo: null
  },

  onLoad: function() {
    this.fetchOfficerData();
  },

  onShow: function() {
    // 每次显示页面时检查登录状态
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({ token });
    }
    else{
      wx.navigateTo({
        url: '/pages/authorize/authorize'
      });
    }
    const cachedOfficer = wx.getStorageSync('currentOfficer');
    if (cachedOfficer) {
      this.updateOfficerInfo(cachedOfficer);
    }
  },
  fetchOfficerData() {
    wx.showLoading({
      title: '加载警员信息...',
    });

    wx.request({
      url: 'http://localhost:8080/api/auth/currentOfficer',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data) {
          const officerData = res.data;
          console.log(officerData);
          // 保存警员信息到缓存
          wx.setStorageSync('currentOfficer', officerData);
          // 更新页面数据
          this.updateOfficerInfo(officerData);
          console.log('警员信息加载成功');
        } else {
          console.error('获取警员信息失败:', res.data);
          this.showErrorToast('获取警员信息失败，请稍后重试');
          // 显示默认提示
          this.setData({ name: '未获取到信息' });
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
        this.showErrorToast('网络连接失败，请检查网络');
        this.setData({ name: '网络异常' });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  updateOfficerInfo(officer) {
    // 假设后端返回的字段：name（姓名）、number（警号）
    this.setData({
      officerInfo: officer,
      name: officer.name || '未知姓名',
      number: officer.officerNumber || '无警号信息',
      status: officer.statusDescription ||'未知',
    });
  },

  showErrorToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
  },
  // 点击"记录上传"时的提示
  showDevelopmentToast() {
    wx.showToast({
      title: '该功能开发中，敬请期待',
      icon: 'none'
    });
  },
  navigateTo(e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({ url });
  },
  onNavigate(e) {
    wx.showLoading({ title: '加载中', mask: true })
    const url = e.currentTarget.dataset.url
    wx.navigateTo({
      url,
      complete: () => wx.hideLoading()
    })
  }
});
    